#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
from flask import Flask, jsonify
from flask import request
import numpy as np
import time
import base64
import json
import cv2
import os
import sys
from plate_detect import PlateParser
# pyinstaller 打包需要此模块(ubuntu x64下打包后运行时提示缺失 models.yolo 时有效)
import models.yolo

app = Flask(__name__)
start = time.time()
device_type = 'cpu'
device_type = ''  # NVIDIA GPU 0

current_exec_abspath = os.path.abspath(sys.argv[0])
current_exec_dirname, current_exec_filename = os.path.split(current_exec_abspath)
current_up_dir, _ = os.path.split(current_exec_dirname)
print('cur_up_path=', current_up_dir)

DB_PATH_Model = 'weights/best.pt'
# DB_PATH_Model = current_up_dir + '/weights/best.pt'
# sys.path.insert(0, current_up_dir + '/weights')
print('模型地址: ', DB_PATH_Model)
g_plate_detect = PlateParser(DB_PATH_Model, device_type)

print('模型加载时间: ', round(time.time() - start, 3))


@app.route('/api/v1/plate/detect', methods=['POST'])
def detect():
    data = request.data
    j_data = json.loads(data)
    imgData = base64.b64decode(j_data['image'])
    np_arr = np.frombuffer(imgData, np.uint8)
    img_np = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)
    conf_threshold = j_data['conf_threshold']

    resultList = g_plate_detect.plate_detect(img_np, conf_threshold)

    errorCode = 0
    errorMessage = 'success'
    result_num = len(resultList)

    result = {}
    resultObj = json.loads(json.dumps(result))
    resultObj['cmd'] = j_data['cmd']
    resultObj['errorCode'] = errorCode
    resultObj['errorMessage'] = errorMessage
    resultObj['data'] = {'result_num': result_num, 'result': []}
    resultObj['data']['result'] = resultList

    return jsonify(resultObj)


def main():
    app.run(host='0.0.0.0', port=5001, debug=False)


if __name__ == '__main__':
    main()
